package com.hollysys.hollimsa.common.exception;

import com.hollysys.hollimsa.common.result.AjaxCodeEnum;
import com.hollysys.hollimsa.common.result.AjaxObject;
import io.fabric8.kubernetes.client.KubernetesClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 统一异常处理
 * @author wangyuxi
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxObject<String> defaultErrorHandler(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxObject.customFail("服务器异常", e.getMessage());
    }

    /**
     *
     * @param e 业务异常
     * @return 异常统一处理结果
     */
    @ExceptionHandler(value = BusinessApiException.class)
    @ResponseBody
    public AjaxObject<String> jsonErrorHandler(BusinessApiException e) {
        log.error(e.getMsg(), e);
        return AjaxObject.customAjax(e.getCode(), e.getMessage(),null );
    }

    /**
     * 统一处理kubernetes 调用异常
     * @param e K8S 异常
     * @return 异常统一处理结果
     */
    @ExceptionHandler(value = KubernetesClientException.class)
    @ResponseBody
    public AjaxObject<String> k8sClientExceptionHandler(KubernetesClientException e) {
        log.error(e.getMessage(), e);
        return AjaxObject.customAjax(AjaxCodeEnum.FAIL.getCode(), e.getMessage(),null );
    }


    /**
     * 统一处理参数验证异常
     * @param e 校验异常
     * @return AjaxObject<String>
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public AjaxObject<String> jsonErrorHandler(MethodArgumentNotValidException e) {
        log.info(e.getMessage(), e);
        List<ObjectError> fieldErrorList = e.getBindingResult().getAllErrors();
        StringBuilder errorList = new StringBuilder();
        for (ObjectError objectError : fieldErrorList) {
            if (!StringUtils.isEmpty(errorList)) {
                errorList.append(",");
            }
            errorList.append(objectError.getDefaultMessage());
        }
        return AjaxObject.basicAjax(AjaxCodeEnum.INVALID_PARAMETERS, errorList.toString());
    }
}

